<?php

class MY_Service extends CI_Service
{
    public function __construct()
    {
        parent::__construct();

        $this->load->helper('json');
        $this->load->library('LogUtil');
        $this->load->library('StrHelper');
        $this->load->driver('cache');

        $this->load->model('Model_configs');
    }

    public function getConfigVal($cid, $needCache = false)
    {
        $cacheKey = 'config_' . $cid;
        $result = $this->cache->memcached->get($cacheKey);
        if (!empty($result) && $needCache) {
            return $result;
        }

        $config = $this->Model_configs->get($cid);
        if (!empty($config) && isset($config['value'])) {
            $this->cache->memcached->save($cacheKey, $config['value'], 86400);
            return $config['value'];
        } else {
            return false;
        }
    }

    public function updateConfigVal($cid, $val)
    {
        $config = $this->Model_configs->get($cid);
        if (!empty($config) && isset($config['value'])) {
            $info['id'] = $config['id'];
            $info['value'] = $val;
            $this->Model_configs->update($info);
            return true;
        } else {
            return false;
        }
    }

    public function getConfigValByKey($key)
    {
        $config = $this->Model_configs->getByParams(['key' => $key]);
        if (!empty($config) && isset($config['value'])) {
            return $config['value'];
        } else {
            return false;
        }
    }

    public function updateConfigValByKey($key, $val)
    {
        $config = $this->Model_configs->getByParams(['key' => $key]);
        if (!empty($config) && isset($config['value'])) {
            $info['id'] = $config['id'];
            $info['value'] = $val;
            $this->Model_configs->update($info);
            return true;
        } else {
            return false;
        }
    }
}
